package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"

	"github.com/urfave/cli"
	onet_app "go.dedis.ch/onet/v3/app"
	onet_log "go.dedis.ch/onet/v3/log"
)

var dataset [][]string

func loadData(path string) error {
	file, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("打开数据文件失败: %v", err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	for {
		record, err := reader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			return fmt.Errorf("CSV读取失败: %v", err)
		}
		dataset = append(dataset, record)
	}
	fmt.Printf("已读取 %d 行数据\n", len(dataset))
	return nil
}

func startDP(c *cli.Context) error {
	config := c.String("config")
	data := c.String("data")

	if data != "" {
		if err := loadData(data); err != nil {
			return err
		}
	}

	// 使用 Drynx 的 app.RunServer 来启动 DP 节点（读取 TOML 配置）
	fmt.Println("启动 DP 节点，配置文件：", config)
	onet_app.RunServer(config)
	return nil
}

func main() {
	app := cli.NewApp()
	app.Usage = "Drynx Data Provider 节点"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "config, c",
			Usage: "DP 配置文件（TOML）",
		},
		cli.StringFlag{
			Name:  "data, d",
			Usage: "上传的数据文件路径（CSV）",
		},
	}
	app.Action = startDP

	if err := app.Run(os.Args); err != nil {
		onet_log.Fatal(err)
	}
}
